package com.orangelife.mobile.shoppingcart.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.CommonJumper;
import com.common.sp.UserSp;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.IntentHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.surrounding.activity.CommercialListActivity;
import com.orangelife.mobile.surrounding.activity.HotGoodsDetailActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.confirmOrder.activity.ShoppingConfirmOrderActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.shoppingcart.bean.ShoppingCartBean;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.util.ToastHelper;

import java.io.Serializable;
import java.util.List;


/**
 * 购物车适配器
 * Created by 吴格非 on 2015/10/10.
 */
public class ShoppingCartAdapter extends BaseExpandableListAdapter {
    private Context mContext;
    private List<ShoppingCartBean> mListChild;
    private ImageView ivSelectAll;
    private TextView btnSettle;
    private TextView tvCountMoney;
    private TextView tvTitle;
    private RelativeLayout rlShoppingCartEmpty;
    private RelativeLayout rlBottomBar;
    private boolean isSelectAll = false;
    private int goodsCount = 0;
    private String selectedCount = "0";
    private String selectedMoney = "0";
    ExpandableListView expandableListView;

    /**
     * 将选择全部的图片视图传入Adapter（这种写法非常不好，增加了几个类之间的耦合度，应该写一个独立的UI组件）
     *
     * @param ivSelectAll
     */
    public void setImageViewSelectAll(ImageView ivSelectAll, TextView btnSettle, TextView tvCountMoney, TextView tvTitle, RelativeLayout rlShoppingCartEmpty, RelativeLayout rlBottomBar, ExpandableListView expandableListView) {
        this.ivSelectAll = ivSelectAll;
        this.btnSettle = btnSettle;
        this.tvCountMoney = tvCountMoney;
        this.tvTitle = tvTitle;
        this.ivSelectAll.setOnClickListener(listener);
        this.tvCountMoney.setOnClickListener(listener);
        this.btnSettle.setOnClickListener(listener);
        this.rlBottomBar = rlBottomBar;
        this.rlShoppingCartEmpty = rlShoppingCartEmpty;
        this.expandableListView = expandableListView;
        setTitle();
        setSettle();
    }

    private void showEmpty(boolean isEmpty) {
        if (isEmpty) {
            expandableListView.setVisibility(View.GONE);
            rlShoppingCartEmpty.setVisibility(View.VISIBLE);
            rlBottomBar.setVisibility(View.GONE);
        } else {
            expandableListView.setVisibility(View.VISIBLE);
            rlShoppingCartEmpty.setVisibility(View.GONE);
            rlBottomBar.setVisibility(View.VISIBLE);
        }
    }

    private void setSettle() {
        selectedCount = "0";
        selectedMoney = "0";
        for (int i = 0; i < mListChild.size(); i++) {
            if (!mListChild.get(i).isInvalidList()) {
                for (int j = 0; j < mListChild.get(i).getGoods().size(); j++) {
                    boolean isSelectd = mListChild.get(i).getGoods().get(j).isChildSelected();
                    if (isSelectd) {
                        String price = mListChild.get(i).getGoods().get(j).getPrice();
                        String num = mListChild.get(i).getGoods().get(j).getNumber();
                        String countMoney = DecimalUtil.multiply(price, num);
                        selectedMoney = DecimalUtil.add(selectedMoney, countMoney);
                        selectedCount = DecimalUtil.add(selectedCount, "1");
                    }
                }
            }
        }
        String countMoney = String.format(Constant.RMB_FLAG+mContext.getResources().getString(R.string.count_money), selectedMoney + "");
        String countGoods = String.format(mContext.getResources().getString(R.string.count_goods), selectedCount + "");
        tvCountMoney.setText(countMoney);
        btnSettle.setText(countGoods);
    }

    public void setTitle() {
        goodsCount = ShoppingCartBiz.getGoodsCount();
        if (!isNetworkOk) {
            goodsCount = 0;
        }
        if (goodsCount == 0) {
            showEmpty(true);
        }
        String title = String.format(mContext.getResources().getString(R.string.shopping_cart_title), goodsCount + "");
        tvTitle.setText(title);
    }

    public ShoppingCartAdapter(Context context, List<ShoppingCartBean> listChild) {
        mContext = context;
        mListChild = listChild;
    }

    public void setList(List<ShoppingCartBean> mListChildGoods) {
        if (mListChildGoods != null) {
            mListChild.clear();
            mListChild.addAll(mListChildGoods);
        }
    }

    @Override
    public int getGroupCount() {
        Log.e(ShoppingCartAdapter.class.getSimpleName(), "group size=" + mListChild.size());
        return mListChild.size();
    }

    @Override
    public int getChildrenCount(int i) {
        Log.e(ShoppingCartAdapter.class.getSimpleName(), i + " child size=" + mListChild.get(i).getGoods().size());
        return mListChild.get(i).getGoods().size();
    }

    @Override
    public Object getGroup(int i) {
        return mListChild.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return mListChild.get(i).getGoods().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        GroupViewHolder holder = null;
        Log.e(ShoppingCartAdapter.class.getSimpleName(), "group text=" + mListChild.get(groupPosition).getMerchantName());
        if (convertView == null) {
            holder = new GroupViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_elv_group_test, parent, false);
            holder.tvGroup = (TextView) convertView.findViewById(R.id.tvShopNameGroup);
            holder.tvEdit = (TextView) convertView.findViewById(R.id.tvEdit);
            holder.ivCheckGroup = (ImageView) convertView.findViewById(R.id.ivCheckGroup);
            convertView.setTag(holder);
        } else {
            holder = (GroupViewHolder) convertView.getTag();
        }
        if (mListChild.get(groupPosition).isInvalidList()) {
            //测试用 INVISIBLE
            convertView.setVisibility(View.INVISIBLE);
            holder.tvGroup.setText("失效列表");
        } else if (mListChild.get(groupPosition).isAllGoodsInvalid()) {
            convertView.setVisibility(View.GONE);
        } else {
            convertView.setVisibility(View.VISIBLE);
        }
        ShoppingCartBiz.checkItem(mListChild.get(groupPosition).isGroupSelected(), holder.ivCheckGroup);
        holder.tvGroup.setText(mListChild.get(groupPosition).getMerchantName());
        holder.tvGroup.setTag(mListChild.get(groupPosition).getMerID());
        if (mListChild.get(groupPosition).isAllGoodsInvalid()) {//正常列表，如果全部失效，则不显示
            holder.ivCheckGroup.setVisibility(View.INVISIBLE);
            holder.tvEdit.setVisibility(View.INVISIBLE);
        } else {
            holder.ivCheckGroup.setVisibility(View.VISIBLE);
            holder.tvEdit.setVisibility(View.VISIBLE);
            holder.ivCheckGroup.setTag(groupPosition);
            holder.ivCheckGroup.setOnClickListener(listener);
            holder.tvEdit.setTag(groupPosition);
            holder.tvEdit.setOnClickListener(listener);
            holder.tvGroup.setOnClickListener(listener);
        }
        //如果是失效列表，则头部也不显示
        if (mListChild.get(groupPosition).isInvalidList()) {
            holder.tvGroup.setText("失效列表");
        }
        boolean isEditing = mListChild.get(groupPosition).isEditing();
        if (isEditing) {
            holder.tvEdit.setText("完成");
        } else {
            holder.tvEdit.setText("编辑");
        }
        return convertView;
    }

    /** 网络是否连接成功； */
    boolean isNetworkOk = true;

    public void setNetworkStatus(boolean isNetworkOk) {
        this.isNetworkOk = isNetworkOk;
        setTitle();
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder holder = null;
        Log.e(ShoppingCartAdapter.class.getSimpleName(), "child text=" + mListChild.get(groupPosition).getGoods().get(childPosition).getGoodsName());
        ShoppingCartBean.Goods goods = mListChild.get(groupPosition).getGoods().get(childPosition);
        boolean isInvalidItem = goods.isInvalidItem();
        if (convertView == null) {
            holder = new ChildViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_elv_child_test, parent, false);
            holder.isInvalidItem = false;
            holder.tvChild = (TextView) convertView.findViewById(R.id.tvItemChild);
            holder.ivCheckGood = (ImageView) convertView.findViewById(R.id.ivCheckGood);
            holder.tvCheckGood = (TextView) convertView.findViewById(R.id.tvCheckGood);
            holder.rlEditStatus = (RelativeLayout) convertView.findViewById(R.id.rlEditStatus);
            holder.llGoodInfo = (LinearLayout) convertView.findViewById(R.id.llGoodInfo);
            holder.ivAdd = (ImageView) convertView.findViewById(R.id.ivAdd);
            holder.ivReduce = (ImageView) convertView.findViewById(R.id.ivReduce);
            holder.tvDel = (TextView) convertView.findViewById(R.id.tvDel);
            holder.tvGoodsParam = (TextView) convertView.findViewById(R.id.tvGoodsParam);
            holder.tvPriceNew = (TextView) convertView.findViewById(R.id.tvPriceNew);
            holder.tvPriceOld = (TextView) convertView.findViewById(R.id.tvPriceOld);
            holder.tvPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tvNum = (TextView) convertView.findViewById(R.id.tvNum);
            holder.tvNum2 = (TextView) convertView.findViewById(R.id.tvNum2);
            holder.ivGoods = (ImageView) convertView.findViewById(R.id.ivGoods);
            holder.tvClearInvalid = (TextView) convertView.findViewById(R.id.tvClearInvalid);
            holder.llInvalidList = (LinearLayout) convertView.findViewById(R.id.llInvalidList);
            convertView.setTag(holder);
        } else {
            holder = (ChildViewHolder) convertView.getTag();
        }

        boolean isBelongInvalidList = mListChild.get(groupPosition).getGoods().get(childPosition).isBelongInvalidList();

        String priceNew = Constant.RMB_FLAG + goods.getPrice();
        String priceOld = Constant.RMB_FLAG + goods.getMkPrice();
        String num = goods.getNumber();

        if (isBelongInvalidList) {
            boolean isLastTempItem = mListChild.get(groupPosition).getGoods().get(childPosition).isLastTempItem();
            if (isLastTempItem) {
                convertView.setVisibility(View.INVISIBLE);
            } else {
                convertView.setVisibility(View.VISIBLE);
                holder.tvCheckGood.setVisibility(View.VISIBLE);
                holder.ivCheckGood.setVisibility(View.INVISIBLE);
                holder.tvPriceNew.setVisibility(View.INVISIBLE);
                holder.tvPriceOld.setVisibility(View.INVISIBLE);
                if (isLastChild) {//如果是最后一个，则显示“清空全部”的按钮；
                    holder.llInvalidList.setVisibility(View.VISIBLE);
                    holder.tvClearInvalid.setOnClickListener(listener);
                } else {
                    holder.llInvalidList.setVisibility(View.GONE);
                }
                holder.llGoodInfo.setVisibility(View.VISIBLE);
                holder.rlEditStatus.setVisibility(View.INVISIBLE);
            }
        } else {
            holder.llInvalidList.setVisibility(View.GONE);
            if (isInvalidItem) {
                convertView.setVisibility(View.GONE);//如果不属于失效列表，却是失效的，就隐藏起来
            } else {
                convertView.setVisibility(View.VISIBLE);
                holder.tvCheckGood.setVisibility(View.INVISIBLE);
                holder.ivCheckGood.setVisibility(View.VISIBLE);
                holder.tvPriceNew.setVisibility(View.VISIBLE);
                holder.tvPriceOld.setVisibility(View.VISIBLE);
                holder.ivCheckGood.setTag(groupPosition + "," + childPosition);
                holder.ivCheckGood.setOnClickListener(listener);
                holder.ivAdd.setTag(goods);
                holder.ivReduce.setTag(goods);
                holder.tvDel.setTag(groupPosition + "," + childPosition);
                holder.tvDel.setOnClickListener(listener);
                holder.ivAdd.setOnClickListener(listener);
                holder.ivReduce.setOnClickListener(listener);
                holder.tvPriceNew.setText(priceNew);
                holder.tvPriceOld.setText(priceOld);
                boolean isEditing = goods.isEditing();
                if (isEditing) {
                    holder.llGoodInfo.setVisibility(View.INVISIBLE);
                    holder.rlEditStatus.setVisibility(View.VISIBLE);
                } else {
                    holder.llGoodInfo.setVisibility(View.VISIBLE);
                    holder.rlEditStatus.setVisibility(View.INVISIBLE);
                }
                holder.llGoodInfo.setTag(mListChild.get(groupPosition).getGoods().get(childPosition).getGoodsID());
                holder.llGoodInfo.setOnClickListener(listener);
                final String tag2 = groupPosition + "," + childPosition;
                holder.llGoodInfo.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        handleDelGoods(tag2);
                        return true;
                    }
                });
                holder.tvNum2.setText(num);
            }
        }

        String text = goods.getGoodsName();
        String pdtDesc = goods.getPdtDesc();
        ShoppingCartBiz.checkItem(mListChild.get(groupPosition).getGoods().get(childPosition).isChildSelected(), holder.ivCheckGood);
        holder.tvNum.setText("X " + num);
        holder.tvGoodsParam.setText(pdtDesc);
        ImageDownloader.getImageDownloader().download(goods.getGoodsLogo(), holder.ivGoods, ImageDownloader.ImageSize.IMAGE_SIZE_EXTRA_SMALL_RECTANGLE_JPG);
        holder.tvChild.setText(text);
        return convertView;
    }


    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            switch (view.getId()) {
                case R.id.tvClearInvalid:
                    ToastHelper.getInstance()._toast("清空失效商品");
                    ShoppingCartBean scb = mListChild.get(mListChild.size() - 1);
                    if (scb != null && scb.isInvalidList()) {
                        ShoppingCartBiz.delInvalidList(scb.getGoods());
//                        scb.setIsAllGoodsInvalid(true);
//                        scb.setIsInvalidList(false);
//                        for (int i = 0; i < scb.getGoods().size(); i++) {
//                            scb.getGoods().get(i).setIsInvalidItem(true);
//                            scb.getGoods().get(i).setIsBelongInvalidList(false);
//                        }
                        mListChild.remove(mListChild.size() - 1);
                        setTitle();
                        setSettle();
                        notifyDataSetChanged();
                    }
                    break;
                case R.id.tvShopNameGroup:
                    IntentHelper.getInstances().intentWithExtra(mContext, CommercialListActivity.class, "merID", String.valueOf(view.getTag()));
                    break;
                case R.id.ivCheckGood:
                    String tag = String.valueOf(view.getTag());
                    if (tag.contains(",")) {
                        String s[] = tag.split(",");
                        int groupPosition = Integer.parseInt(s[0]);
                        int childPosition = Integer.parseInt(s[1]);
                        isSelectAll = ShoppingCartBiz.selectOne(mListChild, groupPosition, childPosition);
                        ShoppingCartBiz.checkItem(isSelectAll, ivSelectAll);
                        setSettle();
                        notifyDataSetChanged();
                    }
                    break;
                case R.id.tvEdit://切换界面
                    int groupPosition2 = Integer.parseInt(String.valueOf(view.getTag()));

                    boolean isEditing = !(mListChild.get(groupPosition2).isEditing());
                    mListChild.get(groupPosition2).setIsEditing(isEditing);
                    if (!isEditing) {

                    }
                    for (int i = 0; i < mListChild.get(groupPosition2).getGoods().size(); i++) {
                        mListChild.get(groupPosition2).getGoods().get(i).setIsEditing(isEditing);
                    }
                    notifyDataSetChanged();
                    break;
                case R.id.ivCheckGroup:
                    final int groupPosition = Integer.parseInt(String.valueOf(view.getTag()));
                    isSelectAll = ShoppingCartBiz.selectGroup(mListChild, groupPosition);
                    ShoppingCartBiz.checkItem(isSelectAll, ivSelectAll);
                    setSettle();
                    notifyDataSetChanged();
                    break;
                case R.id.ivSelectAll:
                    isSelectAll = ShoppingCartBiz.selectAll(mListChild, isSelectAll, (ImageView) view);
                    setSettle();
                    notifyDataSetChanged();
                    break;
                case R.id.tvDel:
                    String tag2 = String.valueOf(view.getTag());
                    handleDelGoods(tag2);
                    break;
                case R.id.ivAdd:
                    ShoppingCartBiz.calcuGoodsNum(true, (ShoppingCartBean.Goods) view.getTag(), ((TextView) (((View) (view.getParent())).findViewById(R.id.tvNum2))));
                    setSettle();
                    break;
                case R.id.ivReduce:
                    ShoppingCartBiz.calcuGoodsNum(false, (ShoppingCartBean.Goods) view.getTag(), ((TextView) (((View) (view.getParent())).findViewById(R.id.tvNum2))));
                    setSettle();
                    break;
                case R.id.btnSettle:
                    if (selectedCount.equals("0")) {
                        ToastHelper.getInstance()._toast("请先选择商品");
                        return;
                    }
                    if(!TextUtils.isEmpty(UserSp.getAccessToken())) {
                        ExitApplication.getInstance().addPaidActivity((Activity) mContext);
                        ((CurryApplication)mContext.getApplicationContext()).setShopping(true);
                        Intent intent = new Intent(mContext, ShoppingConfirmOrderActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString(PaymentModule.PAID_METHOD,PaymentModule.mode[1]);
                        bundle.putSerializable(ShoppingConfirmOrderActivity.SHOPPING_CART_LIST, (Serializable) ShoppingCartBiz.getSettleInfo(mListChild));
                        bundle.putSerializable(ShoppingConfirmOrderActivity.PRODUCT_LIST_IDS, (Serializable) ShoppingCartBiz.getSettleProductID(mListChild));
                        intent.putExtra(ShoppingConfirmOrderActivity.GOODS_PRICES, selectedMoney);
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                    }else{
                        CommonJumper.jumpToLoginWhenExitWithClear(mContext);
                    }
                    break;
                case R.id.tvCountMoney:
                    break;
                case R.id.llGoodInfo:
                    IntentHelper.getInstances().intentWithExtra(mContext, HotGoodsDetailActivity.class, "goodsID", String.valueOf(view.getTag()));
                    break;
            }
        }
    };

    private void handleDelGoods(final String tag2) {
        final ConfirmDialog dialog = new ConfirmDialog(mContext, "温馨提示", "确认删除该商品吗?",
                "取消", "确定");
        dialog.show();

        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {

            @Override
            public void doLeft() {
                dialog.dismiss();
            }

            @Override
            public void doRight() {
                if (tag2.contains(",")) {
                    String s[] = tag2.split(",");
                    int groupPosition3 = Integer.parseInt(s[0]);
                    int childPosition = Integer.parseInt(s[1]);
                    ShoppingCartBiz.delGood(mListChild.get(groupPosition3).getGoods().get(childPosition).getProductID());
                    mListChild.get(groupPosition3).getGoods().remove(childPosition);
                    if (mListChild.get(groupPosition3).getGoods().size() == 0) {
                        mListChild.remove(groupPosition3);
                    }
                    setTitle();
                    setSettle();
                    notifyDataSetChanged();
                    dialog.dismiss();
                }
            }
        });
    }

    public void removeAllItems(){
        mListChild.clear();
        notifyDataSetChanged();
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return false;
    }

    class GroupViewHolder {
        TextView tvGroup;
        TextView tvEdit;
        ImageView ivCheckGroup;
    }

    class ChildViewHolder {
        boolean isInvalidItem;
        TextView tvChild;
        TextView tvGoodsParam;
        ImageView ivCheckGood;
        TextView tvCheckGood;
        LinearLayout llGoodInfo;
        RelativeLayout rlEditStatus;
        ImageView ivAdd;
        ImageView ivReduce;
        TextView tvDel;
        TextView tvPriceNew;
        TextView tvPriceOld;
        TextView tvNum;
        TextView tvNum2;
        ImageView ivGoods;
        TextView tvClearInvalid;
        LinearLayout llInvalidList;
    }
}
